<template>
  <base-page-view class-name="page-container full-cut-goods">
    <view class="sort-container">
      <view class="sort-item" :class="{'active': currentIndex === 1}" @click="handleTab(1)">
        <text>销量</text>
        <view v-if="salesStatus === 1" class="sort-arrow">
          <image class="sort-n-down" src="/static/images/common/sort_n_d.png" />
          <!-- <image class="sort-up" src="/static/images/common/sort_u.png" /> -->
        </view>
        <view v-else-if="salesStatus === 2" class="sort-arrow">
          <!-- <image class="sort-down" src="/static/images/common/sort_u.png" /> -->
          <image class="sort-n-up" src="/static/images/common/sort_n_d.png" />
        </view>
        <view v-else class="sort-arrow">
          <image class="sort-n-down" src="/static/images/common/sort_n_d.png" />
          <!--<image class="sort-n-up" src="/static/images/common/sort_n_d.png" />-->
        </view>
      </view>
      <view class="sort-item" :class="{'active': currentIndex === 2}" @click="handleTab(2)">
        <text>价格</text>
        <view v-if="priceStatus === 1" class="sort-arrow">
          <image class="sort-n-down" src="/static/images/common/sort_n_d.png" />
          <!-- <image class="sort-up" src="/static/images/common/sort_u.png" /> -->
        </view>
        <view v-else-if="priceStatus === 2" class="sort-arrow">
          <!-- <image class="sort-down" src="/static/images/common/sort_u.png" /> -->
          <image class="sort-n-up" src="/static/images/common/sort_n_d.png" />
        </view>
        <view v-else class="sort-arrow">
          <!--<image class="sort-n-up" src="/static/images/common/sort_n_d.png" />-->
          <image class="sort-n-down" src="/static/images/common/sort_n_d.png" />
        </view>
      </view>
      <view class="sort-item" :class="{'active': currentIndex === 0}" @click="handleTab(0)">
        <text>{{ sortTxt }}</text>
        <view class="sort-arrow">
          <image class="sort-n-down" src="/static/images/common/sort_n_d.png" />
          <!--<image class="sort-n-up" src="/static/images/common/sort_n_d.png" />-->
        </view>
      </view>
    </view>
    <view class="cate-panel" :class="{'show': showCate }">
      <view class="model" @touchmove.stop.prevent="" @click="handleCate(item)"></view>
      <view class="cate-container">
        <view class="cate-item" :class="{'active': form.categoryId === ''}" @click="handleCate({id: ''})">全部</view>
        <view
          v-for="(item, index) in categoryList"
          :key="index"
          class="cate-item"
          :class="{'active': form.categoryId === item.id}"
          @click="handleCate(item)">
          {{ item.name }}
        </view>
      </view>
    </view>
    <view v-if="fullCutGoodsDtos.length > 0 && allData.seconds > 0">
      <view class="full-cut-info">
        <view v-if="allData.seconds" class="info-time">
          活动倒计时
          <count-down splitor-color="black" color="white" background-color="black" :second="allData.seconds" @timeup="timeup" />
        </view>
        <!--<view class="info-time">活动时间：{{ allData.startTime | formatDate('MM.dd HH:mm:ss') }} - {{ allData.endTime | formatDate('MM.dd HH:mm:ss') }}</view>-->
        <view class="info-content">{{ allData.promotionName }}</view>
      </view>
      <view class="full-cut-goods">
        <view v-for="(item, index) in fullCutGoodsDtos" :key="index" class="full-cut-goods-item" @click="handleGoods(item)">
          <view class="f-goods-pic">
            <b-image :src="item.imgUrl" width="250" height="250" :need-clip="false" />
          </view>
          <view class="f-goods-info">
            <view>
              <view class="f-goods-title">
                <text v-if="item.goodsType === 2" class="f-goods-pack-title"> 套餐</text>
                {{ item.goodsName }}
              </view>
              <view class="f-goods-tag"><text>满减</text></view>
            </view>
            <view class="f-goods-price">
              <view class="goods-price sign">{{ item.price | formatMoney }}</view>
            <!-- <view class="main-price">￥暂无</view> -->
            </view>
          </view>
          <view class="f-goods-addbtn" @click.stop.prevent="getGoodsDetail(item)">加入购物车</view>
        </view>
        <view v-if="nomore" class="no-more">没有更多了</view>
      </view>
      <view class="f-back-btn" @click="toShopCart">
        <text class="btn-txt-addbtn">{{ btnName }}</text>
      </view>
    </view>
    <view v-else-if="noData" class="no-msg">
      <msg-page :text="msg" />
    </view>
    <commodity-single
      v-if="showSkuPanel"
      ref="singleGoods"
      commodity-type=""
      mask-type="full-cut"
      :single-goods="goodsData"
      :buy-count-ary="buyCountAry"
      @buyCountChange="setBuyCount"
      @buyCountChangeMax="setBuyCountMax"
      @confirm="dialogConfirm"
      @closePopup="showSkuPanel=false"
    />
    <!-- 套餐 -->
    <basePopup v-if="goodsData.type === 2 && showPackage" mask-zindex="100" :show="showPackage" :show-close="false" :has-scroll="true" @close="closePopup">
      <view class="packageGoodsPop maskContainer">
        <commodity-package ref="package" :goods-pack="goodsData.goods_pack" :is-live="true" :goods="goodsData" @hideNumDialog="hideNumDialog" @confirm="dialogConfirm" @close="closePopup" />
        <view v-if="!hidePacketNumDialog" class="packBottom" @touchmove.stop>
          <view class="packBuyNum">
            <view class="limit">
              <view class="p">购买数量<view v-if="goodsData.goods_pack && goodsData.goods_pack.limit_num != 0" class="span">(限购{{ goodsData.goods_pack.limit_num }}件)</view></view>
            </view>
            <view class="buyNum">
              <base-stepper :is-adjust="false" :value.sync="goodsData.goods_pack.buy_num || 1" :size="42" :min="goodsData.goods_pack.min_num || 1" :max="goodsData.goods_pack.limit_num || 999" @inputBlur="blur" @inputFocus="focus" @change="changeQuantity($event)" />
            </view>
          </view>
          <view class="maskBottomBox">
            <block v-if="goodsData.status == 3">
              <view class="maskBottomBtn" @click="packetToLiveOrder('liveAdd')">确定</view>
              <!-- <view class="maskBottomBtn" @click="packetToLiveOrder('liveBuy')">确认</view> -->
            </block>
            <view v-else-if="goodsData.status == 2 || goodsData.status == 1" class="maskBottomBtn green">{{ goodsData.sales_time ? (_parseTime(new Date(goodsData.sales_time * 1000), '{m}月{d}日 {h}:{i}') + '开售') : '该商品还未开售' }}</view>
            <view v-else-if="goodsData.status == 4" class="maskBottomBtn grey">该商品已售罄</view>
            <view v-else class="maskBottomBtn grey">该商品已下架</view>
          </view>
        </view>
      </view>
    </basePopup>
  </base-page-view>
</template>

<script>
import './index.scss'
import { toGoods } from '@/utils/navigateTo'
import { parseTime } from '@/utils/tools'
import CountDown from '@/components/count-down'
import BaseStepper from '@/components/base/base-stepper'
import msgPage from '@/components/msgPage/index'
import CommoditySingle from '../commodity/components/commodity-option/commodity-single'
import CommodityPackage from '../commodity/components/commodity-option/commodity-package'

export default {
  components: {
    CommoditySingle,
    CommodityPackage,
    CountDown,
    BaseStepper,
    msgPage
  },
  data() {
    return {
      currentIndex: 1,
      showCate: false,
      form: {
        categoryId: '',
        fullCutId: '',
        orderBy: 'SALES', // SALES or PRICE
        orderStatus: 'DESC', // ASC(升) or DESC（降）
        pageIndex: 1,
        pageSize: 10
      },
      fullCutGoodsDtos: [],
      allData: {},
      categoryList: [],
      showSkuPanel: false,
      hidePacketNumDialog: false,
      showPackage: false, // 显示套餐
      btnName: '去购物车',
      goodsData: {},
      goodsAllData: {},
      buyCountAry: {
        max: 9999,
        min: 1,
        count: 1
      },
      canBuy: true,
      noData: false,
      nomore: false
    }
  },
  computed: {
    priceStatus() {
      if (this.form.orderBy === 'PRICE') {
        return this.form.orderStatus === 'ASC' ? 2 : 1
      }
      return 2
    },
    salesStatus() {
      if (this.form.orderBy === 'SALES') {
        return this.form.orderStatus === 'DESC' ? 1 : 2
      }
      return 2
    },
    sortTxt() {
      const index = this.categoryList.findIndex(i => i.id === this.form.categoryId)
      if (index > -1) {
        return this.categoryList[index].name
      } else {
        return '全部'
      }
    },
    msg() {
      return this.canBuy ? '暂无商品，请查看其它类目商品' : '活动已结束'
    }
  },
  onLoad(options) {
    if (options.id) {
      this.form.fullCutId = options.id
      this.getFullCutCategory()
      this.getFullcutList()
    } else {
      uni.navigateBack()
    }
    if (options.from === 'detail') {
      this.btnName = '去购物车'
    } else if (options.from === 'cart') {
      this.btnName = '返回购物车'
    }
    this.loading = false
    this.nomore = false
  },
  methods: {
    toShopCart() {
      this.$navigateTo('/pages/cart/index', {})
    },
    _parseTime(val, time) {
      return parseTime(val, time)
    },
    changeQuantity(num) {
      if (this.goodsData && this.goodsData.goods_pack) {
        this.goodsData.goods_pack.buy_num = num
      }
    },
    // 初始化数据
    initData() {
      this.loading = false
      this.nomore = false
      this.fullCutGoodsDtos = []
      this.form.pageIndex = 1
    },
    // 活动页一级类目接口
    async getFullCutCategory() {
      const res = await this.$api.promoteApi.getFullCutCategory()
      if (res.success) {
        this.categoryList = res.data.categoryList
      }
    },
    // 获取满减商品列表
    async getFullcutList() {
      if (this.loading) return
      this.loading = true
      const res = await this.$api.promoteApi.getFullcutList(this.form)
      if (res.success) {
        if (res.data && res.data.fullCutGoodsDtos) {
          this.allData = res.data
          this.fullCutGoodsDtos = this.fullCutGoodsDtos.concat(res.data.fullCutGoodsDtos)
          if (res.data.fullCutGoodsDtos.length < this.form.pageSize) {
            this.nomore = true
          }
        }
        if (res.data && res.data.seconds <= 0) {
          this.canBuy = false
          this.noData = true
        }
      }
      if (this.fullCutGoodsDtos.length === 0) {
        this.noData = true
      }
      this.loading = false
    },
    // tab切换
    handleTab(index) {
      if (index === 0) {
        this.showCate = !this.showCate
      } else {
        this.showCate = false
        if (index === 1) {
          this.form.orderBy = 'SALES'
        } else {
          this.form.orderBy = 'PRICE'
        }
        if (this.form.orderStatus === 'ASC') {
          this.form.orderStatus = 'DESC'
        } else if (this.form.orderStatus === 'DESC') {
          this.form.orderStatus = 'ASC'
        }
        if (this.currentIndex !== index) {
          this.form.orderStatus = 'ASC'
        }
        this.currentIndex = index
        this.initData()
        this.getFullcutList()
      }
    },
    hideNumDialog(val) {
      this.hidePacketNumDialog = val
    },
    packetToLiveOrder(type) {
      this.$refs.package.showPopup(type)
    },
    // 关闭
    closePopup() {
      this.showPackage = false
    },
    // 点击分类
    handleCate(item) {
      if (item) {
        this.form.categoryId = item.id
      }
      this.initData()
      this.getFullcutList()
      this.showCate = false
    },
    // 点击商品
    handleGoods(item) {
      const data = {
        id: item.goods_id || item.goodsId || '',
        from_type: item.from_type || item.fromType || '1',
        activity_id: item.activity_id || item.activityId || '',
        goods_id: item.goods_id || item.goodsId || '',
        goods_type: item.goods_type || item.type || item.goodsType || '',
        promote: item.promotion || '',
        pack_type: item.pack_type || item.packType || ''
      }
      toGoods(data)
    },
    // 点击加入购物车获取商品详情
    async getGoodsDetail(item) {
      if (!this.canBuy) {
        uni.showToast({
          title: '活动时间已结束',
          icon: 'none'
        })
        return
      }
      uni.showLoading({
        title: '加载中'
      })
      const subForm = {
        goods_id: item.goods_id || item.goodsId,
        from_type: item.from_type || item.fromType,
        activity_id: item.activity_id || item.activityId,
        goods_type: item.goods_type || item.type || item.goodsType,
        pack_type: item.pack_type || item.packType
      }

      const res = await this.$api.goodsApi.goodsDetail(subForm)
      uni.hideLoading()
      if (res.success) {
        if (res.data.goods.status !== 3) {
          uni.showToast({
            title: '该商品已下架',
            icon: 'none'
          })
          return
        }
        this.goodsData = res.data.goods
        this.goodsAllData = res.data
        if (this.goodsData.sku_list.length === 1) {
          this.dialogConfirm({
            count: 1,
            selectedSkuItem: this.goodsData.sku_list[0]
          })
        } else {
          if (this.goodsData.type === 2) {
            this.showPackage = true
          } else {
            this.showSkuPanel = true
            this.showSkuTimer = setTimeout(() => {
              this.$refs['singleGoods'].showPopup('')
              clearTimeout(this.showSkuTimer)
            }, 100)
          }
        }
      }
    },
    setBuyCount(num) {
      this.$set(this.buyCountAry, 'count', num)
    },
    setBuyCountMax(num) {
      if (this.buyCountAry.count > num) {
        this.$set(this.buyCountAry, 'count', num)
      }
    },
    async dialogConfirm(buyObj) {
      this.showSkuPanel = false
      const data = {
        goods_id: this.goodsData.goods_id,
        goods_type: this.goodsData.type * 1 === 0 ? '1' : this.goodsData.type,
        sku_code: '',
        activity_id: this.goodsData.activity_id,
        pack_sku: [],
        pack_type: this.goodsData.pack_type * 1 === 0 ? '2' : this.goodsData.pack_type,
        present_sku: '',
        num: buyObj.count,
        from_type: this.goodsData.from_type * 1 === 0 ? '1' : this.goodsData.from_type
      }
      if (buyObj.maskType === 'packageCart') {
        let enableNext = true
        const pack_sku_num = []
        buyObj.packageList.forEach(element => {
          if (!element.selectedSkuItem) {
            enableNext = false
          }
          data.pack_sku.push(element.selectedSkuItem.sku_code)
          pack_sku_num.push(element.selectedSkuItem.package_goods_number)
        })
        if (!enableNext) {
          uni.showToast({
            title: '请完整选择套餐',
            icon: 'none',
            duration: 2 * 1000
          })
          return
        }
        data.num = this.goodsData.goods_pack.buy_num || 1
        data.pack_sku = data.pack_sku.join(',')
        data.pack_sku_num = pack_sku_num.join(',')
      } else {
        if (!buyObj.selectedSkuItem) {
          uni.showToast({
            title: '请选择商品规格',
            icon: 'none',
            duration: 2 * 1000
          })
          return
        }
        data.sku_code = buyObj.selectedSkuItem.sku_code
      }
      if (buyObj.presentList && buyObj.presentList.length) {
        const presentSku = []
        const present_sku_num = []
        buyObj.presentList.forEach(element => {
          presentSku.push(element.selectedSkuItem.sku_code)
          present_sku_num.push(element.selectedSkuItem.package_goods_number)
        })
        data.present_sku_num = present_sku_num.join(',')
        data.present_sku = presentSku.join(',')
      }
      const res = await this.$api.cartApi.addShoppingCart(data)
      if (res.code) {
        return
      }
      uni.showToast({
        title: '加入购物车成功',
        icon: 'none',
        duration: 2 * 1000
      })
    },
    // 倒计时回调
    timeup() {
      this.canBuy = false
    }
  },
  onPullDownRefresh() {
    this.initData()
    this.getFullcutList()
    uni.stopPullDownRefresh()
  },
  onReachBottom() {
    if (this.loading || this.nomore) return
    this.form.pageIndex += 1
    this.getFullcutList()
  }
}
</script>
